package com.erp.database.pos.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.erp.database.pos.domain.POSGoodsDomain;
import com.erp.database.pos.domain.POSSaleDetailDomain;
import com.erp.database.pos.mapper.PosGoodsMapper;
import com.erp.database.pos.mapper.PosSaleDetailMapper;
import com.erp.database.utils.CommonUtil;

/** 
 * @author Buddy
 * @version 2017年10月12日 下午5:20:56 
 */
@Service
public class MiddleTableService {
	
	private static Logger logger = LoggerFactory.getLogger(MiddleTableService.class);
	
	@Autowired
	private PosGoodsMapper posGoodsMapper;//中间表
	@Autowired
	private PosSaleDetailMapper posSaleDetailMapper;

	/**
	 * 如果存在则插入，如果不存在则更新
	 * @param posGoodsList
	 */
	public void insertOrUpdatePosGoods(List<POSGoodsDomain> posGoodsList) {
		int posGoodsSize = posGoodsList.size();
		for(int i=0;i<posGoodsSize;i++){
			POSGoodsDomain posGoods = posGoodsList.get(i);
			String goodsId = posGoods.getGoodsId();
			if(CommonUtil.isEmpty(posGoodsMapper.selectByGoodsId(goodsId))){
				logger.info("--------------------->insert "+goodsId);
				posGoodsMapper.insert(posGoods);
			}else{
				logger.info("--------------------->update "+goodsId);
				posGoodsMapper.updateByPrimaryKey(posGoods);
			}
		}
	}


	public void insertPosSaleDetail(List<POSSaleDetailDomain> posSaleDetailList) {
		List<POSSaleDetailDomain> insertedList = posSaleDetailMapper.selectInserted();//查询已经插入的数据
		logger.info("----------------------------->查询到的已经插入的数据条数"+insertedList.size());
		Map<String, POSSaleDetailDomain> map = new HashMap<String, POSSaleDetailDomain>();
		List<POSSaleDetailDomain> waitInsertList = new ArrayList<POSSaleDetailDomain>();
		if(CommonUtil.isNotEmpty(insertedList)  && CommonUtil.isNotEmpty(posSaleDetailList)){
			for(int i=0,size=insertedList.size();i<size;i++){
				POSSaleDetailDomain inserted = insertedList.get(i);
				String key = inserted.getGoodsID()+inserted.getSaleNO()
						+inserted.getSale_dt()+"";
				map.put(key, inserted);
			}

			for(int j=0,size=posSaleDetailList.size();j<size;j++){
				POSSaleDetailDomain posSaleDetail = posSaleDetailList.get(j);
				String key = posSaleDetail.getGoodsID()+posSaleDetail.getSaleNO()
						+posSaleDetail.getSale_dt()+"";
				POSSaleDetailDomain posSaleDetailDomain  = map.get(key);
				if(CommonUtil.isEmpty(posSaleDetailDomain)){
					waitInsertList.add(posSaleDetail);
				}else{
					logger.info("------------------------->"+posSaleDetail.toString()+"已经有该记录");
				}
			} 
		}
		if(CommonUtil.isNotEmpty(waitInsertList)){
			posSaleDetailMapper.insertList(waitInsertList);
		}
	}


}
